package com.zhsj.OkeHomeConsumption.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hjq.dialog.MessageDialog;
import com.huantansheng.easyphotos.EasyPhotos;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.just.library.WebDefaultSettingsManager;
import com.orhanobut.hawk.Hawk;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.ShareMemberBean;
import com.zhsj.OkeHomeConsumption.empty.ShareMemberBean.DataBeanX.DataBean;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.MDialog;
import com.zhsj.OkeHomeConsumption.other.QRCodeUtil;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.BaseFragment;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import static android.content.Context.CLIPBOARD_SERVICE;
import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * <p>文件描述：<p>
 * <p>作者：xingdx<p>
 * <p>创建时间：2018/11/14<p>
 * <p>更改时间：2018/11/14<p>
 */
public class SharedWebviewTwo extends BaseFragment implements View.OnClickListener {
    // 左标题
    private TextView topbar_textview_leftitle = null;
    // 主标题
    private TextView topbar_textview_title = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    /**
     * @Fields neterror_relative : TODO
     */
    private RelativeLayout neterror_relative = null;
    /**
     * @Fields btn_loadingrefresh : TODO
     */
    private Button btn_loadingrefresh = null;

    private String webview_url;
    /**
     * @Fields duration : TODO
     */
    int duration = 12000; // 开发者需要自己计算音乐播放时长
    /**
     * @Fields countParamHashMap : TODO
     */
    private Map<String, String> countParamHashMap = null;
    /**
     * @Fields mSharedPreferanceUtils : TODO
     */
    private SharedPreferanceUtils mSharePreferanceUtils = null;
    private int tag = -1;
    // 分享
    private RelativeLayout shareapp_topbarRinght = null;
    private String weburltitle;
    private ShareMemberBean.DataBeanX.DataBean data;
    private FormalUserInfo userInfo;
    private AgentWeb mAgentWeb;
    private TimeChecker timeChecker;
    private ClipboardManager mClipboardManager;
    //1 客户端  2合伙人端
    private int type = -1;
    private Bitmap bmp = null;
    private MDialog dialog = null;
    private String textBefore;//正文前
    private String textAfter;//正文后

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data = (ShareMemberBean.DataBeanX.DataBean) getArguments().getSerializable("data");
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
        type = getArguments().getInt("type");
    }

    public static SharedWebviewTwo newInstance(ShareMemberBean.DataBeanX.DataBean data, FormalUserInfo userInfo, int type) {
        Bundle args = new Bundle();
        SharedWebviewTwo fragment = new SharedWebviewTwo();
        args.putSerializable("data", data);
        args.putSerializable("userInfo", userInfo);
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        webview_url = data.getContenTlink() + "?userid=" + userInfo.getId() + "&invite=" + userInfo.getId() + "&type=" + "1" + "&rtype=" + "1";
        weburltitle = data.getTitle();
        textBefore = data.getTextBefore();
        textAfter = data.getTextAfter();
        mAgentWeb = AgentWeb.with(_mActivity, this)//这里需要把 Activity 、 和 Fragment  同时传入
                .setAgentWebParent((ViewGroup) view, new LinearLayout.LayoutParams(-1, -1))// 设置 AgentWeb 的父控件 ， 这里的view 是 RelativeLayout ， 那么需要传入 LinearLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .setReceivedTitleCallback(mCallback)
                .setWebSettings(WebDefaultSettingsManager.getInstance())
                .setWebViewClient(new WebViewClientClass())
                .setSecurityType(AgentWeb.SecurityType.strict) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                .createAgentWeb()//
                .ready()//
                .go(webview_url);
        initView(view);
        initData();
        addLinstener();
    }

    protected int getLayoutId() {
        // TODO Auto-generated method stub
        return R.layout.indexvr_webviewlayout;
    }

    protected void initView(View view) {
        // TODO Auto-generated method stub
        // 初始化标题
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title.setText("正在载入...");
        // 初始化Fragmemt 组件
        shareapp_topbarRinght = (RelativeLayout) view.findViewById(R.id.shareapp_topbarRinght);
        // 断网或者无网络状态下显示页面
        neterror_relative = (RelativeLayout) view.findViewById(R.id.neterror_relative);
        btn_loadingrefresh = (Button) view.findViewById(R.id.btn_loadingrefresh);
    }

    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (topbar_textview_title != null && !TextUtils.isEmpty(title))
                if (title.length() > 10)
                    title = title.substring(0, 10) + "...";
            topbar_textview_title.setText(weburltitle);

        }
    };

    /**
     * @Title: initData @Description: TODO 初始化数据 @param @return void
     * 返回类型 @throws
     */
    @SuppressLint({"SetJavaScriptEnabled", "InlinedApi", "NewApi"})
    protected void initData() {
        // TODO Auto-generated method stub
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        mClipboardManager = (ClipboardManager) _mActivity.getSystemService(CLIPBOARD_SERVICE);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
        if (!weburltitle.equals("")) {
            shareapp_topbarRinght.setVisibility(View.VISIBLE);
            topbar_textview_title.setText(weburltitle);
        }
        mSharePreferanceUtils = new SharedPreferanceUtils(_mActivity);
        // 友盟（计算事件）统计传入的参数

        if (!Utils.isNetWorkConnected(_mActivity)) {
            // 无网络的状态下
            neterror_relative.setVisibility(View.VISIBLE);
        } else {
            // 有网络的状态下
            neterror_relative.setVisibility(View.GONE);
            UserDetailPost();
        }
    }


    /**
     * @Title: addLinstener @Description: TODO 添加视图监听器 @param @return void
     * 返回类型 @throws
     */
    protected void addLinstener() {
        // TODO Auto-generated method stub
        topbar_textview_leftitle.setOnClickListener(this);
        btn_loadingrefresh.setOnClickListener(this);
        shareapp_topbarRinght.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
                // 返回按钮
                if (isFastDoubleClick()) {
                    return;
                }
                WebView mWebView = mAgentWeb.getWebCreator().get();
//                if (mWebView.canGoBack()) {
//                    mWebView.goBack();
//                } else {
                _mActivity.onBackPressed();
//                }

                break;
            case R.id.btn_loadingrefresh:
                if (!Utils.isNetWorkConnected(_mActivity)) {
                    // 无网络的状态下
                    neterror_relative.setVisibility(View.VISIBLE);
                    _mActivity.onBackPressed();
                    showShortToast("网络状态弱，请重试");
                } else {
                    // 有网络的状态下
                    neterror_relative.setVisibility(View.GONE);
                }
                break;
            case R.id.shareapp_topbarRinght:
                if (isFastDoubleClick()) {
                    return;
                }
                // 分享
                show();
                break;
            case R.id.wechat_img:
                if (isFastDoubleClick()) {
                    return;
                }
                dialog.dismiss();
                shareUtils(0, data.getMainTitle(), data.getSubTitle(), data.getContenTlink() + "?userid=" + userInfo.getId() + "&invite=" + userInfo.getId() + "&type=" + "1" + "&rtype=" + "1");
                break;
            case R.id.circle_img:
                if (isFastDoubleClick()) {
                    return;
                }
                dialog.dismiss();
                shareUtils(1, data.getMainTitle(), data.getSubTitle(), data.getContenTlink() + "?userid=" + userInfo.getId() + "&invite=" + userInfo.getId() + "&type=" + "1" + "&rtype=" + "1");
                break;
            case R.id.cop_img:
                if (isFastDoubleClick()) {
                    return;
                }
                dialog.dismiss();
                getConversion(data.getContenTlink() + "?userid=" + userInfo.getId() + "%26invite=" + userInfo.getId() + "%26type=" + "1" + "%26rtype=" + "1");
                break;
            case R.id.erweima_img:
                if (isFastDoubleClick()) {
                    return;
                }
                dialog.dismiss();
                shareApp();
                break;
            default:
                break;
        }
    }


    private class WebViewClientClass extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.loadUrl(request.getUrl().toString());
            } else {
                view.loadUrl(request.toString());
            }
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (error.getPrimaryError() == SslError.SSL_DATE_INVALID
                        || error.getPrimaryError() == SslError.SSL_EXPIRED
                        || error.getPrimaryError() == SslError.SSL_INVALID
                        || error.getPrimaryError() == SslError.SSL_UNTRUSTED) {
                    handler.proceed();
                } else {
                    handler.cancel();
                }
            } else {
                handler.proceed(); // Ignore SSL certificate errors
            }
            super.onReceivedSslError(view, handler, error);
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            if (weburltitle.equals("")) {
                topbar_textview_title.setText(view.getTitle());
                if (url.contains("?id=")) {
                    shareapp_topbarRinght.setVisibility(View.VISIBLE);
                } else {
                    shareapp_topbarRinght.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 转短链
     *
     * @param
     * @return 创建时间：2017/3/8 14:51
     */
    public void getConversion(String url) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("longUrl", url);
        paramMaps.put("longUrl", url);
        // 获取sign签名
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_DUANLIAN, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    if (code.equals("N000000")) {
                        String data = jsonOBJ.optString("data");
                        ClipData clipData = ClipData.newPlainText("OKeHomePartner", textBefore + data + textAfter);
                        mClipboardManager.setPrimaryClip(clipData);
                        new MessageDialog.Builder(getActivity())
                                .setTitle("聚联惠") // 标题可以不用填写
                                .setMessage("内容已经粘贴完毕")
                                .setConfirm("确定")
                                .setCancel(null) // 设置 null 表示不显示取消按钮
                                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                                .setListener(new MessageDialog.OnListener() {

                                    @Override
                                    public void onConfirm(Dialog dialog) {
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onCancel(Dialog dialog) {
                                    }
                                })
                                .show();
                    }
                } catch (JSONException ex) {
                }
            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
            }
        });
    }

    /**
     * 二维码
     */
    public void UserDetailPost() {
        String s = data.getContenTlink() + "?userid=" + userInfo.getId() + "&invite=" + userInfo.getId() + "&type=" + "1" + "&rtype=" + "1";
        Bitmap qrImage = null;
        Resources res = _mActivity.getResources();
        switch (type) {
            case 0:
                bmp = BitmapFactory.decodeResource(res, R.drawable.qrcode_julianhui).copy(Bitmap.Config.RGB_565, true);
                qrImage = QRCodeUtil.createQRImage(s);
                break;
            case 1:
                bmp = BitmapFactory.decodeResource(res, R.drawable.hehuorenimg).copy(Bitmap.Config.RGB_565, true);
                qrImage = QRCodeUtil.createQRImage(s);
                break;
            case 2:
                bmp = BitmapFactory.decodeResource(res, R.drawable.shejishi).copy(Bitmap.Config.RGB_565, true);
                qrImage = QRCodeUtil.createQRImage(s);
                break;
            case 3:
                bmp = BitmapFactory.decodeResource(res, R.drawable.gongzhang).copy(Bitmap.Config.RGB_565, true);
                qrImage = QRCodeUtil.createQRImage(s);
                break;
            case 4:
                bmp = BitmapFactory.decodeResource(res, R.drawable.jiazhaungguanjia).copy(Bitmap.Config.RGB_565, true);
                qrImage = QRCodeUtil.createQRImage(s);
                break;
        }
        /**
         * 给图片添加水印，水印会根据图片宽高自动缩放处理
         *
         * @param watermark     水印
         * @param image         添加水印的图片
         * @param srcImageWidth 水印对应的原图片宽度,即ui制作水印时参考的要添加水印的图片的宽度
         * @param offsetX       添加水印的X轴偏移量
         * @param offsetY       添加水印的Y轴偏移量
         * @param addInLeft     true 在左下角添加水印，false 在右下角添加水印
         * @return 是否成功
         */
        EasyPhotos.addWatermark(qrImage, bmp, 1800, 250, 250, true);

    }

    public void show() {
        dialog = new MDialog(_mActivity);
        //填充对话框的布局
        View inflate = LayoutInflater.from(_mActivity).inflate(R.layout.dialog_shared, null);
        //初始化控件
        inflate.findViewById(R.id.wechat_img).setOnClickListener(this);
        inflate.findViewById(R.id.circle_img).setOnClickListener(this);
        inflate.findViewById(R.id.cop_img).setOnClickListener(this);
        inflate.findViewById(R.id.erweima_img).setOnClickListener(this);
        dialog.setView(inflate);
        //将布局设置给Dialog
//        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow == null) {
            return;
        }
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框

    }

    /**
     * @Title: shareApp @Description: TODO @param @param title
     * 分享标题 @param @param content 分享内容 @param @param url 分享链接 @return
     * void @throws
     */
    private void shareApp() {
        final UMImage image = new UMImage(_mActivity, bmp);//bitmap文件
        new ShareAction(mActivity).setPlatform(0 == 0 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                .withMedia(image)
                .share();
    }


    // type  0:分享微信好友  1： 分享朋友圈
    private void shareUtils(int type, String title, String context, String url) {
        final UMWeb web = new UMWeb(url);
        web.setTitle(title);//标题
        web.setDescription(context);//描述
        web.setThumb(new UMImage(mActivity, R.mipmap.androidicon1));
        new ShareAction(mActivity).setPlatform(type == 0 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                .withMedia(web)
                .share();
    }

    /**
     * @Fields umShareListener : TODO 监听分享后的状态
     */
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            showShortToast("分享活动成功啦");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        //mAgentWeb.clearWebCache()
        super.onDestroyView();
        //  mAgentWeb.destroy();
    }


}
